package com.thz.friend.service.user.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.thz.common.core.constants.Constants;
import com.thz.common.core.enums.ExamListType;
import com.thz.common.core.enums.ResultCode;
import com.thz.common.core.pojo.TableDataInfo;
import com.thz.common.core.result.Result;
import com.thz.common.core.utlis.ThreadLocalUtil;
import com.thz.exception.ApplicationException;
import com.thz.friend.manager.ExamCacheManager;
import com.thz.friend.mapper.exam.ExamMapper;
import com.thz.friend.mapper.report.ReportMapper;
import com.thz.friend.mapper.user.UserExamMapper;
import com.thz.friend.pojo.exam.Exam;
import com.thz.friend.pojo.exam.dto.ExamDTO;
import com.thz.friend.pojo.exam.dto.ExamQueryDTO;
import com.thz.friend.pojo.exam.vo.ExamVO;
import com.thz.friend.pojo.report.Report;
import com.thz.friend.pojo.user.UserExam;
import com.thz.friend.service.user.IUserExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Description
 * @Author thz
 * @Date 2025/3/29
 */
@Service
public class UserExamServiceImpl implements IUserExamService {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private UserExamMapper userExamMapper;

    @Autowired
    private ExamCacheManager examCacheManager;

    @Autowired
    private ReportMapper reportMapper;

    @Override
    public int enter(String token, ExamDTO examDTO) {

        Exam exam = examMapper.selectById(examDTO.getExamId());
        if (exam == null) {
            throw new ApplicationException(Result.failed(ResultCode.FAILED_NOT_EXISTS));
        }
        if (examDTO.getCourseId() != null){
            if(exam.getStartTime().isBefore(LocalDateTime.now())) {
                throw new ApplicationException(Result.failed(ResultCode.EXAM_STARTED));
            }
        }

        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);

        UserExam userExam = userExamMapper.selectOne(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getExamId, examDTO.getExamId())
                .eq(UserExam::getUserId, userId));

        if (examDTO.getCourseId() != null){
            if (userExam != null) {
                throw new ApplicationException(Result.failed(ResultCode.USER_EXAM_HAS_ENTER));
            }
        }

//        Report reports = reportMapper.selectOne(new LambdaQueryWrapper<Report>()
//                .eq(Report::getExamId, examDTO.getExamId()).eq(Report::getCreateUser,userId));
//        if (reports == null) {
//            Report report = new Report();
//            report.setExamId(examDTO.getExamId());
//            reportMapper.insert(report);
//        }

        examCacheManager.addUserExamCache(userId, examDTO.getExamId());
        userExam = new UserExam();
        userExam.setExamId(examDTO.getExamId());
        userExam.setUserId(userId);
        return userExamMapper.insert(userExam);
    }

    @Override
    public TableDataInfo list(ExamQueryDTO examQueryDTO) {
        // 1.1先从redis中查询数据
        // 1.2获取用户id
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        // 1.3设置状态
        examQueryDTO.setType(ExamListType.USER_EXAM_LIST.getValue());
        // 查询redis中的页码判断
        Long total = examCacheManager.getListSize(examQueryDTO.getType(), userId);

        List<ExamVO> examVOList;
        if (total == null || total <= 0) {
            // total不存在 redis中没有
            // 从数据库中查找
            PageHelper.startPage(examQueryDTO.getPageNum(), examQueryDTO.getPageSize());
            examVOList = userExamMapper.selectUserExamList(userId);
            // 更新缓存
            examCacheManager.refreshCache(examQueryDTO.getType(), userId);
            total = new PageInfo<>(examVOList).getTotal();
        } else {
            // total存在 获取redis中的数据
            examVOList = examCacheManager.getExamVOList(examQueryDTO, userId);
            total = examCacheManager.getListSize(examQueryDTO.getType(), userId);
        }
        if (CollectionUtil.isEmpty(examVOList)) {
            return TableDataInfo.empty();
        }
        return TableDataInfo.success(examVOList, total);
    }

}
